import { getPexelsHintApi } from "@/apis/index.js"
import { defineStore } from "pinia"
import { computed, ref } from "vue"

const HISTORY_STORAGE_KEY = 'search_history'

export const useSearchStore = defineStore('search', () => {
  // State
  const history = ref<string[]>([])
  const result = ref<string[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const hasHistory = computed(() => history.value.length > 0)

  const hasResults = computed(() => result.value.length > 0)

  // Actions

  /**
   * 从 localStorage 加载搜索历史
   */
  function loadHistory() {
    try {
      const storedHistory = localStorage.getItem(HISTORY_STORAGE_KEY)
      if (storedHistory) {
        history.value = JSON.parse(storedHistory)
      }
    } catch (e) {
      console.error('Failed to load search history from localStorage', e)
      history.value = []
    }
  }

  /**
   * 将当前历史记录保存到 localStorage
   */
  function _saveHistory() {
    try {
      localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(history.value))
    } catch (e) {
      console.error('Failed to save search history to localStorage', e)
    }
  }

  /**
   * 添加一个搜索词到历史记录
   * @param query - 搜索词
   */
  function addToHistory(query: string) {
    const trimmedQuery = query.trim()
    if (!trimmedQuery) return

    // 如果已存在，先移除，再添加到最前面，实现置顶效果
    const existingIndex = history.value.findIndex(
      (item) => item.toLowerCase() === trimmedQuery.toLowerCase()
    )
    if (existingIndex > -1) {
      history.value.splice(existingIndex, 1)
    }

    // 添加到数组开头
    history.value.unshift(trimmedQuery)

    // 限制历史记录数量，例如最多20条
    if (history.value.length > 20) {
      history.value.pop()
    }

    _saveHistory()
  }

  /**
   * 删除指定索引的历史记录
   * @param index - 要删除的记录的索引
   */
  function deleteHistoryItem(index: number) {
    history.value.splice(index, 1)
    _saveHistory()
  }

  /**
   * 清空所有搜索历史
   */
  function clearHistory() {
    history.value = []
    _saveHistory()
  }

  /**
   * 执行搜索
   * @param query - 搜索词
   */
  async function performSearch(query: string) {
    const trimmedQuery = query.trim()
    if (!trimmedQuery) return

    isLoading.value = true
    error.value = null
    // 清空上次结果
    result.value = [] 

    try {
      addToHistory(trimmedQuery)
      const response = await getPexelsHintApi(trimmedQuery)
      result.value = response.result
    } catch (e) {
      console.error('Search failed:', e)
      error.value = '搜索失败，请稍后重试。'
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 清空搜索结果
   */
  function clearResults() {
    result.value = []
  }


  // 初始化时加载历史记录
  loadHistory()

  return {
    history,
    result,
    isLoading,
    error,
    hasHistory,
    hasResults,
    performSearch,
    deleteHistoryItem,
    clearHistory,
    clearResults,
  }
})